﻿using System;
using System.IO;
using System.Text;
using System.Threading.Tasks;
using Nancy;
using QQ2564874169.Json;

namespace QQ2564874169.WebFx.Nancy.Responses
{
    public class JsonResponse : Response
    {
        public static Func<JsonResponse, string> JsonConverter { get; set; }
        public object Model { get; }
        private const string DefaultContentType = "application/json";
        private Encoding _encoding;

        static JsonResponse()
        {
            JsonConverter = resp => JsonHelper.ToJson(resp.Model);
        }

        public JsonResponse(object model, Encoding encoding = null)
        {
            if (model == null)
                throw new ArgumentNullException(nameof(model));
            Model = model;
            StatusCode = HttpStatusCode.OK;
            Contents = GetJsonContents;
            ContentType = DefaultContentType;
            _encoding = encoding;
            if (_encoding != null)
            {
                ContentType += "; charset=" + encoding.WebName;
            }
        }

        public override Task PreExecute(NancyContext context)
        {
            var ua = context.Request.Headers.UserAgent ?? "";
            if (ua.ToLower().Contains("msie"))
            {
                ContentType = ContentType.Replace(DefaultContentType, "text/plain");
            }
            return base.PreExecute(context);
        }

        private void GetJsonContents(Stream stream)
        {
            var json = JsonConverter(this);
            var data = (_encoding ?? Encoding.UTF8).GetBytes(json);
            stream.Write(data, 0, data.Length);
        }
    }
}
